package com.atguigu.study.controller;

import com.atguigu.study.service.ChatAssistant;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.concurrent.TimeUnit;

/**
 * @author 60301
 * @auther zzyy
 * @create 2025-02-21 22:44
 */
@RestController
@Slf4j
public class ChatModelController {
    @Resource
    private StreamingChatModel streamingChatModel;
    @Resource
    private ChatAssistant chatAssistant;

    @GetMapping(value = "/chatstream/chat2")
    public Flux<String> chat2(@RequestParam("prompt") String prompt, HttpServletResponse response) {
        // 设置响应的字符编码
        response.setCharacterEncoding("UTF-8");

        chatAssistant.chat2(prompt).subscribe(
            // onPartialResponse
            System.out::println,
            // onError
            Throwable::printStackTrace,
            // onCompleteResponse
            () -> System.out.println("onCompleteResponse")
        );

        /*chatAssistant.chat2(prompt).subscribe(
                str -> {
                    // 这里的代码会在每次有新的String时执行
                    System.out.println(str);
                },
                error -> {
                    // 这里的代码会在发生错误时执行
                    System.err.println("Error occurred: " + error.getMessage());
                },
                () -> {
                    // 这里的代码会在Flux完成时执行
                    System.out.println("All strings processed onComplete.");
                }
        );*/

        // 暂停几秒钟线程
        try {
            TimeUnit.SECONDS.sleep(7);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return chatAssistant.chat2(prompt);
    }

    @GetMapping(value = "/chatstream/assistant2")
    public void assistant2(@RequestParam(value = "prompt", defaultValue = "hello, 邯郸有什么好吃的？") String prompt) {
        streamingChatModel.chat(prompt, new StreamingChatResponseHandler() {

            @Override
            public void onPartialResponse(String partialResponse) {
                System.out.println("onPartialResponse: " + partialResponse);
            }

            @Override
            public void onCompleteResponse(ChatResponse completeResponse) {

            }

            @Override
            public void onError(Throwable error) {

            }
        });
        // 暂停几秒钟线程
        try {
            TimeUnit.SECONDS.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
 
